<?php

namespace App\Logic;

use Common\Model\ContractModel;

class ContractLogic extends ContractModel 
{

	protected function _initialize() 
	{
		parent::_initialize();
	}

	public function getContractData($data = array()) 
	{   	
		$result = array(
			'status' => 0,
			'contract_id' => $data['number']
		);
		
		$raw = $this->where(array('contract_number' => $data['number']))->getItem();
		
		if(!empty($raw))
		{
			$result['status'] = $raw['contract_status'];
		}
		else
		{
			if($this->updateContract($data) === false)
			{
				return false;
			} 
		}
		
		return $result;
	}

	public function getDataByPar($number = '')
	{
		$where = array('contract_number'=>$number);
		
		return $this->where($where)->getItem();
	}

	public function updateContract($data = array())
	{   
		$result = $this->updateByPK($data);
		return $result;
	}

	public function updateByParm($where = array(),$parm = array())
	{
		$parm = $this->create($parm);
		return $this->updateRecordByParm($where,$parm);
	}

	public function updateByPK($data = array())
	{
		$data = $this->create($data);
		return $this->updateRecord($data);
	}
	
	public function getSecretKey() 
	{
		return '72969e04baa8b6e43fae34e1969d56a6';
	}
	
	public function checkSign($data) 
	{
		$clientSign = $data['sign'];
		
		$sign = $this->getSign($data);
		
		return $clientSign === $sign;
	}
	
	public function getSign($data) 
	{
		unset($data['sign']);
		
		$sk = $this->getSecretKey();
		
		ksort($data);
		$query = '';
		
		foreach ($data as $key => $item) 
		{
			$query .= "&{$key}={$item}";
		}
	
		$query = trim($query,'&');
		$query .= $sk;
		
		return md5($query);
	}
	
	public function checkPara($query = array())
	{
		$raw = array();
		
		$raw['number'] = isset($query['contract_id']) ? $query['contract_id'] : $query['contractId'];
		
		if( empty($raw['number']) )
		{
			$this->error = '合同编号不能为空';
			
			return false;
		}
		
		// 兼容低版本接口
		$raw['type'] = isset($query['type']) ? $query['type'] : $query['commodityModel'];
		$raw['cardid'] = isset($query['cardid']) ? $query['cardid'] : $query['certificateCard'];
		$raw['commodity_type'] = isset($query['commodity_type']) ? $query['commodity_type'] : $query['commodityType'];
		$raw['brand'] = isset($query['brand']) ? $query['brand'] : $query['commodityBrand'];
		$raw['name'] = isset($query['name']) ? $query['name'] : $query['customerName'];
		$raw['loan_type'] = isset($query['loan_type']) ? $query['loan_type'] : $query['loanType'];
		$raw['down_pay'] = isset($query['down_pay']) ? $query['down_pay'] : $query['downPayment'];
		$raw['total_money'] = isset($query['total_money']) ? $query['total_money'] : $query['commodityPrice'];
		
		if( empty($raw['down_pay']) )
		{
			unset($raw['down_pay']);
		}
		else
		{
			$raw['down_pay'] = str_replace(",","",$raw['down_pay']);
		}
		
		if( empty($raw['total_money']) )
		{
			unset($raw['total_money']);
		}
		else
		{
			$raw['total_money'] = str_replace(",","",$raw['total_money']);
		}
		
		return $raw;
	}

}
